import $tools from "./tools.js";
import $var from "./var.js";
import $skip from "./skip.js";
import request from "./request.js";
import $lang from "./lang.js";

//公共方法
var $fun = {
	getThis() {
		let pages = getCurrentPages(); // 获取当前打开过的页面路由数组
		let page = pages[pages.length - 1] // 获取当前页面路由，也就是最后一个打开的页面路由
		return page;
	},
	getRouter(){
		let routes = getCurrentPages();
		let router = routes[routes.length - 1];
		return router.route ? router.route : 'index';
	},
	imgUrl(url) {
		if (!url) return '';
		return url.indexOf('http') != -1 ? url : $var.apiUrl + url;
	},
	// 复制
	copy(item, title) {
		// #ifdef H5
		let url = item;
		let oInput = document.createElement('input');
		oInput.value = url;
		document.body.appendChild(oInput);
		oInput.select();
		document.execCommand("Copy");
		uni.showToast({
			title: title || '复制成功',
			duration: 1000,
			position: 'top',
			icon: 'none'
		});
		oInput.remove()
		// #endif
		// #ifndef H5
		uni.setClipboardData({
			data: item,
			showToast: false,
			success: function() {
				uni.showToast({
					title: title || '复制成功',
					duration: 1000,
					position: 'top',
					icon: 'none'
				});
			}
		});
		// #endif

	},
	// 提示弹窗
	showNotice(data) {
		if (data && JSON.stringify(data) != '{}') {
			uni.$emit('gt_notice', data)
			setTimeout(() => uni.hideLoading(), 300);
		}
	},
	getLocal(params) {
		var _this = this;
		if ($var.locationInfo && $var.locationInfo.time && $var.locationInfo.time + 300000 > new Date().getTime()) {
			params && params.fun();
		} else {
			uni.getSetting({
				success(res) {
					console.log(res);
					if (!res.authSetting['scope.userLocation']) {
						$var.locationInfo = {
							lat: 0,
							long: 0,
							time: 0
						}
						console.log('定位未授权');
						params && params.fun();
					}
				}
			});
			uni.getLocation({
				type: 'gcj02',
				success(res) {
					$var.locationInfo = {
						lat: res.latitude,
						long: res.longitude,
						time: new Date().getTime()
					}
					console.log($var.locationInfo);
					params && params.fun();
				}
			})
		}

	},
	//获取URl参数
	getQueryString(name) {
		// #ifdef H5
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		var r = window.location.search.substr(1).match(reg);
		if (r != null) return unescape(r[2]);
		return null;
		// #endif

	},
	setPageParams(key, params) { //设置页面传参
		$var.page_params[key] = params;
		uni.setStorageSync('page_params', $var.page_params)
	},
	getPageParams(key, isDelete = false) { //设置页面传参
		let params = $var.page_params[key];
		if (isDelete == true) {
			$fun.delPageParams(key)
		}
		return params
	},
	delPageParams(key) {
		$var.page_params[key] = '';
		uni.setStorageSync('page_params', $var.page_params)
	},
	showMsg(msg, option = {}) { //提示信息
		let duration = option.duration || 2000;
		uni.showToast({
			title: msg,
			icon: option.icon || 'none',
			mask: option.mask || true,
			position: option.position || 'center',
			duration: duration,
		});
		if (option.skip) {
			setTimeout(() => { $skip.to(option.skip) }, duration)
		}
		// uni.showModal({
		// 	title: '',
		// 	showCancel: false,
		// 	content: msg,
		// 	success: function(res) {
		// 		if (res.confirm) {
		// 			console.log(option)
		// 			if (option.skip) {
		// 				$skip.to(option.skip)
		// 			}
		// 		} else if (res.cancel) {
		// 			// console.log('用户点击取消');
		// 		}
		// 	}
		// });
	},
	t(name) {
		let msg = $lang.messages[$lang.locale];
		if (msg[name]) {
			return msg[name];
		}
		console.log("lang", $lang.locale, name)
		return name;
	},
	async showModal(params) { //警告确认并跳转
		let msg = typeof params == 'string' ? params : params.msg;
		return new Promise((resolve) => {
			uni.showModal({
				content: msg,
				showCancel: true,
				cancelText: $fun.t('取消'),
				confirmText: $fun.t('确认'),
				success(r) {
					if (r.confirm) {
						params.skip && $skip.to(params.skip);
						resolve(true)
					} else {
						resolve(false)
					}
				}
			});
		})

	},
	callMobile(mobile) {
		uni.makePhoneCall({
			phoneNumber: mobile
		})
	},
	logout() { //退出
		uni.clearStorageSync();
		$var.token_info = null;
		$fun.init();
	},
	setShopHistory(row) {
		if ($var.history.shop.length > 69) {
			$var.history.shop = $var.history.shop.splice(0, 68)
		}
		for (var index in $var.history.shop) {
			if ($var.history.shop[index].sid == row.sid) {
				$var.history.shop.splice(index, 1);
			}
		}
		$var.history.shop.unshift(row)
		uni.setStorageSync('history', $var.history)
	},
	showImgs(params, current) { //预览图片
		if (typeof params == 'string') {
			params = params.split(',');
		}
		for (let i in params) {
			params[i] = $fun.imgUrl(params[i]);
		}

		uni.previewImage({
			current: current || 0,
			urls: params,
			indicator: 'number'
		});
	},
	setCache(key, val, cache_time = 0) { //设置 缓存
		$var[key] = val;
		val = $tools.AES.encrypt(JSON.stringify(val), $var.miyao.a, $var.miyao.b)
		uni.setStorageSync(key, val)
	},
	getCache(key, isDelete = false) { //获取 缓存
		let val = uni.getStorageSync(key)
		if (isDelete) uni.removeStorageSync(key);
		if (val) {
			// console.log(typeof val);
			if (typeof val != 'string') {
				return null;
			}
			val = $tools.AES.decrypt(val, $var.miyao.a, $var.miyao.b);
			if (!val) return '';
			val = JSON.parse(val);
		}
		return val;
	},
	deleteCache(key) {
		uni.removeStorageSync(key);
	},
	getPlatform() { //获取 平台类型
		var systemInfo = uni.getSystemInfoSync();
		// #ifdef H5
		if (systemInfo.ua && systemInfo.ua.match(
				/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
			)) {
			return systemInfo.ua.match(/MicroMessenger/i) == "MicroMessenger" ? 'wechart' : 'mobile';
		} else {
			return 'PC'
		}
		// #endif
		// #ifndef H5
		return systemInfo.platform;
		// #endif

	},
	getReferrerCode() { //获取 推广码
		let referrer_code = $fun.getQueryString('referrer_code');
		if (referrer_code) {
			$fun.setCache('referrer_code', referrer_code)
			return referrer_code;
		} else {
			return $fun.getCache('referrer_code') || '';
		}
	},
	getScreenSize() { //获取 屏幕尺寸
		var systemInfo = uni.getSystemInfoSync();
		return systemInfo.safeArea;
	},
	getDeviceId() { //获取 设备编号
		let deviceId = uni.getStorageSync('__deviceId');
		if (deviceId) return deviceId;
		var systemInfo = uni.getSystemInfoSync();
		uni.setStorageSync('__deviceId', systemInfo.deviceId);
		return systemInfo.deviceId;
	},
	init() { //初始化公共变量
		$var.referrer_code = $fun.getReferrerCode();
		$var.user_info = $fun.getCache('user_info') || null;
		$var.auth_info = $fun.getCache('auth_info') || null;
		$var.platform = $fun.getPlatform();
		$var.size = $fun.getScreenSize();
		$var.lang = uni.getStorageSync('lang') || $var.lang;
		// setTimeout(()=>{ uni.setLocale($var.lang); },30)

		$var.deviceId = $fun.getDeviceId();
		$var.page_params = uni.getStorageSync('page_params') || {};
		$var.history = uni.getStorageSync('history') || $var.history;
	}
};
$fun.init();
// 暴露属性和方法

export default $fun;